#coding=utf-8
from stvalidator import isValidDealfromSina
from stutils import *
from stsettings import datadir

DEALDIR = "%s/deal"%datadir

tb_deal = '''
create table if not exists deal
(id integer primary key,
 code text not null,
 name text not null,
 
 date text not null,
 time text not null,
 
 price float not null,
 volume int not null,
 amount float not null,
 bors text not null
);
'''

def get_namebycode(code):
    set_django_environ()
    from stdj.stock.models import Share
    s = Share.objects.get(code=code)
    return s.name

def deal2db(con, code, exdate):
    fn = '%s/%s/%s.csv'%(DEALDIR, code, exdate)
    data = csv2data(fn)
    
    for d in data:
        isValidDealfromSina(d)
    
    name = get_namebycode(code)    
    c = con.cursor()
    for d in data:
        c.execute('''insert into deal (code, name, date, time, price, volume, amount, bors)
                     values(?,?,?,?,?,?,?,?)
                  ''',
                  (code, name, exdate, d[0], float(d[2]), int(d[1]), int(d[1])*float(d[2]), d[3])
                 )
    con.commit()
    
if __name__ == '__main__':
    dbfn = '%s/deal.db'%datadir
    con = get_dbconnector(dbfn)
    con.cursor().execute(tb_deal)
    con.close()